<template>
  <div class="padding30px">
    <a-card>
      <!-- 搜索区域 -->
      <a-form :model="searchForm" layout="inline" @submit.prevent="handleSearch">
        <a-form-item label="角色名">
          <a-input v-model:value="searchForm.roleName" placeholder="输入角色名" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" htmlType="submit">搜索</a-button>
        </a-form-item>

        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>

    </a-card>
    <a-card title="角色管理">
      <!-- 操作按钮 -->
      <a-button type="primary" @click="openAddModal" style="margin-bottom: 16px">新增角色</a-button>
      <a-button @click="deleteSelect" style="margin-left: 16px"
        :disabled="rowSelectionSelecRow.length == 0">批量删除</a-button>
      <!-- 表格 -->
      <a-table :dataSource="roles" :columns="columns" :pagination="pagination" :row-selection="rowSelection"
        rowKey="reId" bordered @change="handleTableChange">
        <!-- 自定义列渲染 -->
        <template #bodyCell="{ column, record }">
          <!-- 创建时间格式化 -->
          <template v-if="column.dataIndex === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <!-- 权限ID列表显示 -->
          <template v-if="column.dataIndex === 'permissions'">
            <a-tag v-for="id in record.permissions" :key="id">{{ id }}</a-tag>
          </template>

          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'edit'">
            <a-button @click="openEditModal(record)">编辑</a-button>

            <a-button style="margin-left: 20px;" @click="openEditPrm(record)">编辑权限</a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑模态框 -->
    <a-modal :title="isEditMode ? '编辑角色' : '新增角色'" :open="modalVisible" @ok="handleSubmit" @cancel="handleCancel">
      <a-form ref="formRef" :model="currentFormData" :rules="formRules" layout="vertical">
        <a-form-item label="角色名称" name="reName">
          <a-input v-model:value="currentFormData.reName" />
        </a-form-item>

        <!-- <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="currentFormData.remark" :rows="4" />
        </a-form-item> -->

        <!-- 可扩展：权限选择 -->
        <!-- 此处可以添加权限选择器，后续可扩展 -->

        <!-- <a-form-item label="状态">
          <a-switch v-model:checked="currentFormData.status" />
        </a-form-item> -->
      </a-form>
    </a-modal>
    <a-drawer v-model:open="open" class="custom-class" root-class-name="root-class-name" :root-style="{ color: 'blue' }"
      style="color: red" title="权限选择" placement="right">
      <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys"
        checkable :tree-data="treeData">
        <template #title="{ title, key }">
          {{ title }}
        </template>
      </a-tree>
      <!-- {{ checkedKeys }} -->
      <a-button style="margin-top: 20px;" @click="updateParm()">保存</a-button>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getRoleListApi,
  saveOrUpdateRoleApi,
  deleteRoleApi,
  getRoleInfoApi,
  updateRolePermissionsApi
} from '#/api/object/role'

import { getAccessMenusApi } from '#/api/object/router';

// 通用 CRUD 钩子
import { crud } from '#/components/crud'

// 图片上传组件（此处暂时未用到，保留未来扩展可能）
// import ImageUpload from '#/components/ImageUpload.vue'

// 初始化搜索表单
const initSearchForm = {
  roleName: '',
}

const pagination = {
  current: 1,
  pageSize: 10,
  total: 0,
}
// 使用 useCrud 管理数据和操作
const {
  dataSource: roles,
  searchForm,
  selectedRowKeys: rowSelectionSelecRow,
  modalVisible,
  isEditMode,
  formData: currentFormData,
  loadData,
  handleTableChange,
  handleSearch,
  resetSearch,
  deleteSelected: deleteSelect,
  openAddModal,
  openEditModal,
  handleSubmit,
  handleCancel,
} = crud({
  getList: getRoleListApi,
  create: saveOrUpdateRoleApi,
  update: saveOrUpdateRoleApi,
  delete: deleteRoleApi,
}, initSearchForm)

// 表单验证规则
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称' }
  ],
}

// 表格列配置
const columns = [
  { title: '角色名称', dataIndex: 'reName', key: 'reName', align: 'center' },
  // { title: '备注', dataIndex: 'remark', key: 'remark', align: 'center' },
  // { title: '权限ID', dataIndex: 'permissions', key: 'permissions', align: 'center' },
  // { title: '创建时间', dataIndex: 'createTime', key: 'createTime', align: 'center' },
  { title: '操作', dataIndex: 'edit', key: 'edit', align: 'center' },
]

// 行选择配置
const rowSelection = {
  onChange: (selectedRowKeys) => {
    rowSelectionSelecRow.value = selectedRowKeys
  }
}

// 时间格式化函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} `
}
// 页面挂载时加载数据
onMounted(() => {
  loadData()
})




//编辑权限
const editItem = ref()
const expandedKeys = ref([]);
const selectedKeys = ref([]);
const checkedKeys = ref([]);
const treeData = ref([]);
const open = ref(false)

const convertToTreeData = (menus) => {
  return menus.map(menu => ({
    ...menu,
    title: menu.nickName,
    key: String(menu.id),
    children: menu.children ? convertToTreeData(menu.children) : [],
  }));
};

const openEditPrm = async (item) => {
  open.value = true
  // console.log("item", item)
  editItem.value = item
  checkedKeys.value = []
  const rsp = await getRoleInfoApi(item.reId)
  // console.log(rsp.list)
  checkedKeys.value = rsp.list?.map(res => {
    return `${res.rtId}`
  }) || []
  const menus = await getAccessMenusApi()
  // console.log("menus", convertToTreeData(menus.data))
  treeData.value = convertToTreeData(menus.data)
}
const updateParm = () => {
  const parm = checkedKeys.value.map(key => {
    return {
      reId: editItem.value.reId,
      rtId: key,
      raPermission: "all"
    }
  })
  updateRolePermissionsApi(parm).then(res => {
    loadData()
    message.success('操作成功')
    open.value = false
  })



}

</script>

<style scoped>
.padding30px {
  padding: 30px;
}
</style>
